import { Component } from 'react'
import { GET_NEWS } from '@/store/actionType'
import { Button } from 'antd'
import { connect } from 'react-redux'
import { getNewsList } from '@/api'
import store from '@/store'
import { IState } from '@/store/reducer/news'

interface IProps {
	news: IState
	updateNews: () => void
}

class NewsConnect extends Component<IProps, IState> {
	constructor(props: IProps) {
		super(props)
		const {
			news: { news },
		} = store.getState()
		this.state = { news }
	}
	render() {
		const {
			news: { news = [] },
			updateNews,
		} = this.props
		return (
			<div>
				<Button onClick={updateNews}>刷新store中news</Button>
				{news.map((o, i) => (
					<div key={i}>
						<span>{o.name}</span>
						<span>{o.id}</span>
					</div>
				))}
			</div>
		)
	}
}

const mapStateToProps = (state: { news: IState }) => {
	return {
		news: state.news,
	}
}

const mapDispatchToProps = (dispatch: Function) => {
	return {
		updateNews: async () => {
			const news = await getNewsList()
			dispatch({ type: GET_NEWS, news })
		},
	}
}

export default connect(mapStateToProps, mapDispatchToProps)(NewsConnect)
